package com.hugy.test.entity.es;

import lombok.Data;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

/**
 * @author YangChao
 * @create 2018-06-02 22:47
 **/
@Data
public class Term implements Cloneable, Serializable {

    /**
     * 字段
     */
    private String column;

    /**
     * 值
     */
    private Object value;

    /**
     * 链接类型
     */
    private TermEnum type = TermEnum.AND;

    /**
     * 条件类型
     */
    private TermTypeEnum termType = TermTypeEnum.EQ;

    /**
     * 嵌套的条件
     */
    private List<Term> terms = new LinkedList<>();

    public Term or(Term term) {
        term.setType(TermEnum.OR);
        terms.add(term);
        return this;
    }

    public Term or(String term, Object value) {
        return or(term, TermTypeEnum.EQ, value);
    }

    public Term or(String term, TermTypeEnum termType, Object value) {
        Term queryTerm = new Term();
        queryTerm.setTermType(termType);
        queryTerm.setColumn(term);
        queryTerm.setValue(value);
        queryTerm.setType(TermEnum.OR);
        terms.add(queryTerm);
        return this;
    }

    public Term and(Term term) {
        term.setType(TermEnum.AND);
        terms.add(term);
        return this;
    }

    public Term and(String term, Object value) {
        return and(term, TermTypeEnum.EQ, value);
    }

    public Term and(String term, TermTypeEnum termType, Object value) {
        Term queryTerm = new Term();
        queryTerm.setTermType(termType);
        queryTerm.setColumn(term);
        queryTerm.setValue(value);
        queryTerm.setType(TermEnum.AND);
        terms.add(queryTerm);
        return this;
    }

    public static Term build(String column, Object value) {
        return build(column, TermTypeEnum.EQ, value);
    }

    public static Term build(String column, TermTypeEnum termType, Object value) {
        Term term = new Term();
        term.column = column;
        term.value = value;
        term.termType = termType;
        return term;
    }

    public Term addTerm(Term term) {
        terms.add(term);
        return this;
    }

    @Override
    public Term clone() {
        Term term = new Term();
        term.setColumn(column);
        term.setValue(value);
        term.setType(type);
        term.setTermType(termType);
        terms.forEach(t -> term.addTerm(t.clone()));
        return term;
    }

}
